package com.dengpp.pdform.holder;

import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.dengpp.pdform.R;
import com.dengpp.pdform.adapter.AttributeAdapter;
import com.dengpp.pdform.base.BaseAttributeViewHolder;
import com.dengpp.pdform.config.AttributeConfig;

public class NumberViewHolder extends BaseAttributeViewHolder {
    private EditText editText;
    private TextView tvValue;
    private TextView tvTitle;
    private TextWatcher textWatcher;
    private AttributeConfig currentAttribute;

    public NumberViewHolder(@NonNull View itemView) {
        super(itemView);
        tvTitle = itemView.findViewById(R.id.tv_title);
        editText = itemView.findViewById(R.id.edit_text);
        tvValue = itemView.findViewById(R.id.tv_value);
    }

    @Override
    public void bind(AttributeConfig attribute, boolean isEditMode, AttributeAdapter.OnAttributeChangeListener listener) {
        // 保存当前绑定的属性
        this.currentAttribute = attribute;

        // 移除旧的 TextWatcher
        if (textWatcher != null) {
            editText.removeTextChangedListener(textWatcher);
        }


//        if(attribute.isHide()){
//            tvTitle.setText(attribute.getTitle());
//            editText.setText(attribute.getValue() != null ? attribute.getValue().toString() : "");
//            tvValue.setText(attribute.getValue() != null ? attribute.getValue().toString() : "");
//
//            tvTitle.setVisibility(View.GONE);
//            editText.setVisibility(View.GONE);
//            tvValue.setVisibility(View.GONE);
//            return;
//        }

        // 使用带星号的标题
        tvTitle.setText(getTitleWithRequiredStar(attribute.getTitle(), attribute.isRequired()));

        if (isEditMode && attribute.isEditable()) {
            editText.setVisibility(View.VISIBLE);
            tvValue.setVisibility(View.GONE);

            // 设置输入类型为数字
            editText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);

            // 先设置文本，再添加监听器
            editText.setText(attribute.getValue() != null ? attribute.getValue().toString() : "");
            if (attribute.getHint() != null) {
                editText.setHint(attribute.getHint());
            }

            // 创建新的 TextWatcher
            textWatcher = new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {}

                @Override
                public void afterTextChanged(Editable s) {
                    String input = s.toString();

                    // 确保当前属性仍然匹配
                    if (currentAttribute != attribute) {
                        return;
                    }

                    // 验证输入
                    boolean isValid = validateNumberInput(input, attribute);
                    if (!isValid) {
                        editText.setError(getNumberValidationMessage(attribute));
                    } else {
                        editText.setError(null);
                    }

                    if (listener != null) {
                        listener.onAttributeChanged(attribute.getKey(), input);
                    }
                }
            };

            editText.addTextChangedListener(textWatcher);
        } else {
            editText.setVisibility(View.GONE);
            tvValue.setVisibility(View.VISIBLE);
            tvValue.setText(attribute.getValue() != null ? attribute.getValue().toString() : "");
        }
    }

    /**
     * 在 ViewHolder 被回收时清理资源
     */
    @Override
    public void onViewRecycled() {
        super.onViewRecycled();
        if (textWatcher != null) {
            editText.removeTextChangedListener(textWatcher);
            textWatcher = null;
        }
        currentAttribute = null;
    }

    /**
     * 验证数字输入
     */
    private boolean validateNumberInput(String input, AttributeConfig attribute) {
        if (input == null || input.isEmpty()) {
            return true; // 空值在必填验证中处理
        }

        try {
            double value = Double.parseDouble(input);

            // 验证数值范围
            if (attribute.getMinValue() != 0 && value < attribute.getMinValue()) {
                return false;
            }

            if (attribute.getMaxValue() != 0 && value > attribute.getMaxValue()) {
                return false;
            }

            // 验证类型
            String validationRule = attribute.getValidationRule();
            if (validationRule != null) {
                switch (validationRule) {
                    case "integer":
                        return input.matches("-?\\d+");
                    case "positive_integer":
                        return input.matches("\\d+") && value >= 0;
                    case "decimal":
                        return input.matches("-?\\d+(\\.\\d+)?");
                    case "positive_decimal":
                        return input.matches("\\d+(\\.\\d+)?") && value >= 0;
                    default:
                        return input.matches(validationRule);
                }
            }

            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    /**
     * 获取数字验证错误消息
     */
    private String getNumberValidationMessage(AttributeConfig attribute) {
        if (attribute.getValidationMessage() != null) {
            return attribute.getValidationMessage();
        }

        String validationRule = attribute.getValidationRule();
        if (validationRule != null) {
            switch (validationRule) {
                case "integer":
                    return "请输入整数";
                case "positive_integer":
                    return "请输入正整数";
                case "decimal":
                    return "请输入数字";
                case "positive_decimal":
                    return "请输入正数";
            }
        }

        // 范围验证消息
        StringBuilder message = new StringBuilder();
        if (attribute.getMinValue() != 0 && attribute.getMaxValue() != 0) {
            message.append("请输入").append(attribute.getMinValue())
                    .append("到").append(attribute.getMaxValue()).append("之间的数字");
        } else if (attribute.getMinValue() != 0) {
            message.append("请输入不小于").append(attribute.getMinValue()).append("的数字");
        } else if (attribute.getMaxValue() != 0) {
            message.append("请输入不大于").append(attribute.getMaxValue()).append("的数字");
        } else {
            message.append("请输入有效的数字");
        }

        return message.toString();
    }
}